import { Component, OnInit, Input, Output, EventEmitter, ElementRef } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { config } from '../smartadmin.config';

declare var $: any;
@Component({
	selector: 'sa-select2',
	templateUrl: './select2.component.html',
	styleUrls: ['./select2.component.css'],
})
export class Select2Component implements OnInit {
    @Input() select2ElementID:string; // select2元素ID
    @Input() select2Lable:string = '车牌号码'; // label文本[名称],默认车牌号码
	@Input() icon:string = "fa fa-car"; // 选项前图标,默认"fa fa-car",小车的图标
	@Input() matchSearch:boolean = false; // 是否打开模糊匹配功能,默认关闭
	@Input() matchSearchURL:string = "stats/carListByCarNumber.html" ;// 模糊匹配数据[动态数据]接口,默认车辆接口
	@Input() dataURL:string; // 静态数据接口
	@Input() queryParam:any; // 静态数据接口传参
	@Input() paramFormat:any = {id:'id',text:'name'}; // 数据解析格式(格式中转),id:交互数据,text:展示数据
	@Input() dataList:any; // 静态数据
	@Output() optionSelected = new EventEmitter();
	selectDataList = []; // 静态数据
	optionData: any; // 选中选项
	constructor(private jsonApiService: JsonApiService, private el: ElementRef) {}
	//将时间传递给父组件
	sendParent() {
		this.optionSelected.emit(this.optionData);
	}
	ngOnInit() {
		System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
			System.import('assets/js/select2-zh-CN.js').then(() => {
			    if(this.dataList && this.dataList.length){
			        this.selectDataList = [];
			        for(let i = 0; i < this.dataList.length; i++) {
                        let obj = {
                            'id': this.dataList[i][this.paramFormat.id],
                            'text': this.dataList[i][this.paramFormat.text],
                            'option': this.dataList[i],
                        }
                        this.selectDataList.push(obj);
                    }
			        this.initSelect2()
			    }else if(this.dataURL){
			        this.queryDataList().then(()=>{this.initSelect2()})
			    }else{
			        this.initSelect2()
			    }
			});
		});
	}
	ngOnChanges() {
	    let that = this;
	    if(this.dataList && this.dataList.length){
            for(let i = 0; i < this.dataList.length; i++) {
                let obj = {
                    'id': this.dataList[i][this.paramFormat.id],
                    'text': this.dataList[i][this.paramFormat.text],
                    'option': this.dataList[i],
                }
                this.selectDataList.push(obj);
            }
            $("#"+this.select2ElementID).empty();
            $("#"+this.select2ElementID).prepend("<option value=''>请选择</option>");
            System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
                System.import('assets/js/select2-zh-CN.js').then(() => {
                    $("#"+this.select2ElementID).select2({
                        language: "zh-CN",
                        data: that.selectDataList, //为Select添加数据
                        templateResult: function(state){
                            if(!state.id) {
                                return state.text;
                            }
                            return $('<span><i class="'+ that.icon +' green"></i>&nbsp;&nbsp;' + state.text + '</span>');
                        },
                    })
                })
            })
        }
	}

	ngOnDestroy() {}

    // 获取数据,select2选项数据
    queryDataList() {
        var that = this;
        return new Promise(function(resolve, reject) {
            that.queryParam = that.queryParam ? that.queryParam : null;
            that.jsonApiService.http_obj(that.dataURL, that.queryParam).subscribe(data => {
                let resultList = data.data;
                that.selectDataList = [];
                for(let i = 0; i < resultList.length; i++) {
                    let obj = {
                        'id': resultList[i][that.paramFormat.id],
                        'text': resultList[i][that.paramFormat.text],
                        'option': resultList[i],
                    }
                    that.selectDataList.push(obj);
                }
                resolve();
            })
        })
    }
	// 初始化select2配置
	initSelect2() {
		var that = this;
		if(!this.dataURL && !this.dataList) {
		    $("#"+this.select2ElementID).select2({
                language: "zh-CN",
                placeholder: "请选择",
                allowClear: true,
                minimumInputLength: 2, //最少2个字符，select2才显示查询的内容
                ajax: {
                    url: config.BaseURL + this.matchSearchURL,
                    dataType: 'json',
                    delay: 50,
                    method: "POST",
                    xhrFields: {
                        withCredentials: true
                    },
                    data: function(params) {
                        return {
                            "carNumber": params.term // search term
                        };
                    },
                    processResults: function(data, params) {
                        var options = new Array();
                        // 小于10个数量才判断重复
                        if(data.data.length<=10){
                            let arr = []
                            let sameCar = []
                            // 判断相同的车牌号
                            for (let index = 0; index < data.data.length; index++) {
                                let car = data.data[index];
                                if(arr.indexOf(car.carNumber)!=-1){
                                    sameCar.push(car.carNumber)
                                }else{
                                    arr.push(car.carNumber);
                                }
                            }
                            $(data.data).each(function(index, car) {
                                if(sameCar.indexOf(car.carNumber)!=-1){
                                    options.push({
                                        'id': car.deviceId,
                                        'text': car.carNumber+"["+car.parentName+"]",
                                        'option': car
                                    })
                                }else{
                                    options.push({
                                        'id': car.deviceId,
                                        'text': car.carNumber,
                                        'option': car
                                    })
                                }
                            });
                        }else{
                            $(data.data).each(function(index, car) {
                                options.push({
                                    'id': car.deviceId,
                                    'text': car.carNumber,
                                    'option': car
                                })
                            });
                        }
                        return {
                            results: options //获取查询后的结果
                        };
                    },
                    cache: true
                },
                templateResult:function(state){
                    if(!state.id) {
                        return state.text;
                    }
                    return $('<span><i class="'+ that.icon +' green"></i>&nbsp;&nbsp;' + state.text + '</span>');
                },
            }).on("select2:select", function(e) {
                that.optionData = e.params.data;
                if(that.optionData.text.indexOf('[') > 0){
                    that.optionData.text = that.optionData.text.split('[')[0];
                }
                that.sendParent();
            });
		} else {
		    $("#"+this.select2ElementID).select2({
                language: "zh-CN",
                placeholder: "请选择",
                allowClear: true,
                data: this.selectDataList, //为Select添加数据
                templateResult:function(state){
                    if(!state.id) {
                        return state.text;
                    }
                    return $('<span><i class="'+ that.icon +' green"></i>&nbsp;&nbsp;' + state.text + '</span>');
                },
            }).on("select2:select", function(e) {
                that.optionData = e.params.data;
                that.sendParent();
            });
		}
	}
	// 擦除车牌号码所选值
	del_carNumber() {
		this.optionData = {};
		//采用简单粗暴的方法清除;官方推荐的方法失效
		var str = $("<span class='select2-selection__placeholder'>请选择</span>");
		$('#'+this.select2ElementID).val("");
		$("#select2-"+this.select2ElementID+"-container").empty();
		$("#select2-"+this.select2ElementID+"-container").attr("title", "");
		$("#select2-"+this.select2ElementID+"-container").prepend(str);
		this.sendParent()
	}
}